package com.axin.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.axin.blog.api.domain.WebUser;
import com.axin.common.core.exception.ServiceException;
import com.axin.web.annotation.IgnoreAuth;
import com.axin.web.service.WebTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 * @author lixin
 * @date 2021-07-01 15:35
 */

public class ApiAuthorizationInterceptor implements HandlerInterceptor {

	@Autowired
	private WebTokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		response.setStatus(HttpServletResponse.SC_OK);

		IgnoreAuth annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
		} else {
			return true;
		}

		//如果有@IgnoreAuth注解，则不验证token
		if (annotation != null) {
			return true;
		}

		//从header中获取token
		String token = tokenService.getToken(request);
		if (StrUtil.isBlank(token)) {
			throw new ServiceException("你还未登录，请先登录", 401);
		}

		//查询token信息
		WebUser user = tokenService.getLoginUser(request);
		if (user == null) {
			throw new ServiceException("token失效，请重新登录", 401);
		}

		//设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute("user", user);

		return true;
	}

}
